class ForecastTestsController < ApplicationController
  skip_before_filter :authenticate_user!, :only => [:save_test_logs]
  
  # GET /test_logs
  # GET /test_logs.json
  def index
    @test_logs = TestLog.includes(:test_base_data)
    if !params[:base_data_type].nil?
      @test_logs = @test_logs.includes(:test_base_data).where('test_base_data.base_data_type' => params[:base_data_type])
    end
    if !params[:algorithm_name].nil?
      @test_logs = @test_logs.where(:algorithm_name => params[:algorithm_name])
    end
    if !params[:algorithm_version].nil?
      @test_logs = @test_logs.where(:algorithm_version => params[:algorithm_version])
    end
    if !params[:forecast_horizon].nil?
      @test_logs = @test_logs.where(:forecast_horizon => params[:forecast_horizon])
    end
    if !params[:device_model].nil?
      @test_logs = @test_logs.where(:device_model => params[:device_model])
    end
    
    below_60 = 0
    @test_logs.each do |test_log|
      if TestLog.get_mean_absolute_error(test_log, params[:forecast_horizon]) <= 60.to_d
        below_60 += 1
      end
    end
    @below_60_percent = (below_60.to_d / @test_logs.count.to_d)*100
    
    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @test_logs }
    end
  end

  # GET /test_log
  # GET /test_log.json
  def show
    @test_log = TestLog.find params[:test_log_id]
    
    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @test_log }
    end
  end

  # GET /test_forecast_result_chart_data.json
  def test_forecast_result_chart_data
    test_log = TestLog.find params[:test_log_id]
    test_base_data = Marshal.load test_log.test_base_data.base_data
    forecasted_data = Marshal.load test_log.forecasted_data
  
    data_table = []
    index = 0
    
    test_base_data.each do |value|
      data_table.push [index, value, nil]
      index+=1
    end
    
    index -= test_log.forecast_horizon
    
    forecasted_data.each do |value|
      data_table.push [index, nil, value]
      index+=1
    end

    respond_to do |format|
      format.json { render :json => data_table.to_json }
    end
  end

  # POST /save_test_logs.json
  def save_test_logs
    if params[:auth_key] == EMPATHY_SYNC_AUTH_KEY
      saved_list = Array.new #Control list of saved test logs using Id's
      
      params[:test_logs].each do |test_log_json|
        new_test_log = TestLog.new_with_json! test_log_json
        if new_test_log.save
          saved_list.push test_log_json[:id]
        end
      end
      
      respond_to do |format|
          format.json { render :json => saved_list.to_json }
      end
    else
      respond_to do |format|
          format.json { render :text => 'Not authorized access' }
      end
    end
  end
end
